package com.bgdCA.auth.interceptor;


import com.bgdCA.annotation.BiccAuth;
import com.bgdCA.auth.entity.TokenInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AuthInterceptor
 * @Description TODO
 * @Author AlvinZheng
 * @Date 2020/8/2 0:37
 * @Version 1.0
 **/
@Order(3)
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("调用AuthInterceptor拦截器");
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            BiccAuth authAnnotation = handlerMethod.getMethod().getAnnotation(BiccAuth.class);
            // 如果方法上的注解为空 则获取类的注解
            if (authAnnotation == null) {
                log.info("获取方法上注解为空，开始尝试获取类上注解");
                authAnnotation = handlerMethod.getMethod().getDeclaringClass().getAnnotation(BiccAuth.class);
            }
            if (authAnnotation != null) {
                String[] Targetauth = authAnnotation.auth();
                log.info("已获取注解,开始判断权限");
                TokenInfo tokenInfo = (TokenInfo) request.getAttribute("tokenInfo");
                String userAuth = tokenInfo.getAuthorization();
                System.out.println(userAuth);
                if (userAuth == "" && userAuth == null) {
                    //权限为空
                    System.out.println("权限为空");
                    return false;
                }
                if (authCheck(userAuth, Targetauth)) {
                    //包含权限允许放行
                    System.out.println("包含权限");

                    return true;
                }
                System.out.println("权限不通过");
                //权限不通过
                return false;
            }
        }
        System.out.println("end1!!!!!");
        return false;
    }

    private boolean authCheck(String userAuth, String[] targetAuth) {
        System.out.println("!!!!"+userAuth);
        System.out.println("!!!!t"+targetAuth);
        for (String s : targetAuth) {
            System.out.println("s:"+s);
            System.out.println(userAuth.contains(s));
            if (userAuth.contains(s)) {
                return true;
            }
        }
        return false;
    }

}
